package com.cc.send;

import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @author CHENCHEN
 * @company 北京学佳澳教育科技
 * @create 2023-03-21 16:47
 * Demo:
 *      rabbitMQSender.sendDirectMessage("This is a direct message", DIRECT_EXCHANGE, DIRECT_ROUTING_KEY);
 *      rabbitMQSender.sendTopicMessage("This is a topic message", TOPIC_EXCHANGE, "topic.routing.key.sample");
 *      rabbitMQSender.sendFanoutMessage("This is a fanout message", FANOUT_EXCHANGE);
 *      rabbitMQSender.sendDeadLetterMessage("This is a dead letter message", DIRECT_EXCHANGE, DEAD_LETTER_ROUTING_KEY);
 *
 *      Map<String, Object> headers = new HashMap<>();
 *      headers.put("header-key", "header-value");
 *      rabbitMQSender.sendHeadersMessage("This is a headers message", HEADERS_EXCHANGE, headers);
 */
@Component
public class RabbitMQSender {

    @Autowired
    private AmqpTemplate amqpTemplate;

    public void sendDirectMessage(String message, String exchange, String routingKey) {
        amqpTemplate.convertAndSend(exchange, routingKey, message);
    }

    public void sendTopicMessage(String message, String exchange, String routingKey) {
        amqpTemplate.convertAndSend(exchange, routingKey, message);
    }

    public void sendFanoutMessage(String message, String exchange) {
        amqpTemplate.convertAndSend(exchange, "", message);
    }

    public void sendHeadersMessage(String message, String exchange, Map<String, Object> headers) {
        amqpTemplate.convertAndSend(exchange, "", message, msg -> {
            MessageProperties messageProperties = msg.getMessageProperties();
            headers.forEach(messageProperties.getHeaders()::put);
            return msg;
        });
    }

    public void sendDeadLetterMessage(String message, String exchange, String routingKey) {
        amqpTemplate.convertAndSend(exchange, routingKey, message);
    }

}